import socket
import socketserver
import threading
from queue import Queue

import json

from channels.auth import login
from django.shortcuts import render
from django.template.context_processors import request
from twisted.conch.ssh.agent import value

import multiprocessing
# 定义接收的设备发送数据的字典列表
device_rev_list = {
    'device': {
        'models': "QHYJ1000",
        'Data': 'None',
    }
}
device_rev_list_data = {
    'ip': 'ip',
    'data': 'data',
    'fault': 'fault',
    'trace': 'trace',
}

# 创建一个Python对象
device_login = {
    "submit": "verify",
}
device_login_err = {
    "err": "Login data exception",
}

message_queues = {}  # 保存所有客户端的消息队列

# json数据校验
def is_valid_json(json_string):
    try:
        json.loads(json_string)
        return True
    except (json.JSONDecodeError, TypeError, ValueError):
        return False


class ChatHandler(socketserver.BaseRequestHandler):
    def setup(self):
        super().setup()
        # self.client_id = self.client_address[0] #连接客户端的IP地址
        device_rev_list[self.client_address[0]] = device_rev_list_data
        print(device_rev_list)
        # 将Python对象序列化为JSON字符串
        login_json = json.dumps(device_login)
        # 发送数据到客户端 # 将JSON字符串转换为UTF-8字节串
        self.request.sendall((login_json.encode('utf-8')))

    def handle(self):
        try:
            while True:
                self.rev_data = self.request.recv(1024).strip()
                # 尝试将字节序列解码为字符串
                print(self.rev_data.decode('utf-8'))
                print(json.dumps(self.rev_data.decode('utf-8')))
                if not self.rev_data.decode('utf-8'):  # 客户端可能已经关闭了连接
                    return
                if is_valid_json(self.rev_data.decode('utf-8')):  # 是正常的json
                    print("可以序列化")
                    rev_data_serialize =   json.loads(self.rev_data.decode('utf-8'))
                    print(rev_data_serialize['data'])
                    device_rev_list[self.client_address[0]]['data'] = rev_data_serialize['data']
                    print(device_rev_list)
                else:
                    print("不可以序列化")
                    self.request.close()  # 异常直接关闭连接！
                    return

        except (ConnectionResetError, socket.error) as e:  # 处理连接断开或其他套接字错误
            print("连接异常{e}".format(e=e))

        finally:
            # 无论是否发生异常，都尝试关闭套接字
            self.request.close()


def finish(self):
    # print(self.client_address[0])
    # del device_rev_list[self.client_address[0]]
    super().finish()
    key_value = device_rev_list.pop(self.client_address[0], None)
    print(key_value)
    print(device_rev_list)
    # del message_queues[self.client_id]


class MyTCPServer(socketserver.ThreadingTCPServer):
    def server_bind(self):
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)
        self.server_address = self.socket.getsockname()


def server_init():
    HOST, PORT = "localhost", 9999
    server = MyTCPServer((HOST, PORT), ChatHandler)
    print("聊天服务器已启动...")
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.start()


server_init()
